<?php
/**
 *设计思路：
 *1，获取不需要实例化的模块
 *    1.1，实例化模型（如果需要）
 *    1.2，实例化模块字段数组（如果需要）
 * 2，查询思路
 *    2.1，判断是否需要实例化模块，如果不需要就直接显示页面，否则继续
 *    2.2，判断是否需要生成查询条件
 *    2.3，进入查询
 * @author Eayon
 *
 */
namespace Agent\Controller;
use Org\Recour\RecourController;
 
abstract class CommonBaseController extends RecourController {
	private  $map; // 查询对象
	private $model; // 实例化对象
	private $list = '';
	private  $order = '';
	private $fields;//当前模型对应数据库的字段数组
	protected  $config = '';
	
	public function __construct() {
		header ( "content-type:text/html;charset=utf-8" );
		if(!$this->init_show()){
			$this->error();
		}
		parent::__construct ();
	    $this->init();
	}
	
	/**
	* 对配置文件进行处理
	*@param
	*@author  Eayon
	*@since 1.0
	*@return 
	*/
	protected function __config($config){
		$this->config = array_merge($this->config,$config);
// 		dump($this->config);
// 		die();
		$this->setModel();
		/*处理掉不能传入进来的参数*/
		if($this->config['neglect_fields'] !== false){
			$neglect_fields = explode(',', $this->config['neglect_fields']);
			if(IS_POST){
				foreach ($neglect_fields as $value) {
					unset($_POST[$value]);
				}
			}else{
				foreach ($neglect_fields as $value) {
					unset($_GET[$value]);
				}
			}
		}
	}
	
	/**
	*  获得添加视图
	*@param
	*@author  Eayon
	*@since 1.0
	*@return 
	*/
	public function add() {
		$this->rand = util_rand_number();
		$this->show_dispaly();
	}
	
	/**
	* 添加一个记录
	*@param
	*@author  Eayon
	*@since 1.0
	*@return 
	*/
	public function insert($data=null){
			if ($this->model->create ($data) &&  ($id  = $this->model->add()) !== false) {
	             return  $this->config['show']?$this->show_redirect() : $id;
			} else {
				return  $this->config['show']?$this->show_redirect() : false;
			}
	}
	
	/**
	 *添加一个记录的时候判断是不是需要排序如果要，那么就要先计算排序的字段值
	 *@param
	 *@author  Eayon
	 *@since 1.0
	 *@return
	 */
	public function _before_insert(){
		$sort = $this->config['sort'];
		/*如果没有排序字段就用做任何处理*/
		if(in_array($sort, $this->fields) ){
			$max_sort = $this->get_max_sort($sort);
				//给排序值赋值
				if (! empty ( $_POST )){
					$_POST[$sort] = $max_sort +1;
				}else{
					$_GET[$sort] = $max_sort +1;
				}
		}
		
		if($this->config['insert_time'] !== false){
				$arr = explode(',', $this->config['insert_time']);
				foreach ($arr as $value) {
					if(in_array($value, $this->fields)){
							$time =  date('Y-m-d H:i:s', time());
							//给排序值赋值
							if (! empty ( $_POST )){
								$_POST[$value] = $time;
							}else{
								$_GET[$value] = $time;
							}
					}	
				}
		}
	}
	
	/**
	* 获得排序的号
	*@param $sort 排序字段
	*@author  Eayon
	*@since 1.0
	*@return 
	*/
	protected function get_max_sort($sort){
		$num = $this->model->count();
		if($num == 0){//如果还没有记录就从1开始
			return 1;
		}else{//有记录就拿到当前记录最大的排序值
			$_result = $this->model->order($sort.' desc')->limit(1)->select();
			$max_sort = $_result[0][$sort];
			return $max_sort+1;
		}
	}
	

	/**
	* 说明：批量删除用户数据，不管是有多少条数据统一使用这个
	注意：系统默认使用的软删除，没有特殊说明
	*@param
	*@author  Eayon
	*@since 1.0
	*@return 
	*/
	public function foreverdelete()
	{
			$pk=$this->model->getPk();//获得这个模块的主键，一定要有主键才可以使用
			$id=$_REQUEST[$pk];  //存放要删除的ID，可以多个
			if(isset($id))//判断id是否存在
			{
				$condition = array($pk=>array('in',explode(',',$id))); //删除条件，形如 id in 1,2,5,6....
				$search = $this->_search();
				unset($search[$pk]);
				$condition = array_merge($condition,$search);
				
				if(!in_array('is_del', $this->fields)){//判断是否需要软删除，如果不需要软删除就不用删除图片直接做标记
					$result = $this->model->where($condition)->select();//获得所有的记录来删除图片
					/*删除需要删除的记录*/
					if($this->model->where($condition)->delete() !== false){
						/*对需要删除的记录的图片做处理*/
						if($this->config['img_fields']){
							$imgNameArr = explode(',',$this->config['img_fields']);//所有可能存在图片的数组
							foreach ($result  as $value){//删除所有的图片
								foreach ($imgNameArr as $value1){//获取所有需要删除图片的字段的
									if(!util_isEmptyString($value[$value1])){//判断这个字段是否存在
										$this->delfile($value[$value1]);//删除图片
									}
								}
							}
						}
						//$this->success ( "删除成功!", $this->show_dispaly() );
						$this->show_redirect();
					}else{
						$this->show_redirect();
						//$this->error("删除失败!", $this->show_dispaly());
					}
				}else{
					/*删除需要删除的记录*/
					$data[$this->config['del_field']] = 1;
					if($this->model->where($condition)->save($data)  !== false){
						$this->success ( "删除成功!", $this->show_dispaly());
					}else{
						$this->error('删除失败!', $this->show_dispaly());
					}
				}
			}else{
				util_404();//错误页面
			}
	}
	
	/**
	* 获取到一个编辑页面
	*@param
	*@author  Eayon
	*@since 1.0
	*@return 
	*/
	public function edit()
	{
	//	$this->map = $this->_search (); // 生成查询对象
		$this->map['id'] = I('id');//添加id条件
		 
		$list = $this->get_fields_model()->where ($this->map);
		if($this->config['relation']){//是否需要使用关联模型
			$list = $list->relation($this->config['relation']);
		}
		$bean = $list ->find();
		$this->vo=$bean;
		$this->rand = util_rand_number();
		$this->show_dispaly();
	}
	
	/**
	 * 修改操作,表单必须是post请求
	 *@param $data如果有传入操作数组就不用做动态的数据处理
	 *@author  Eayon
	 *@since 1.0
	 *@return
	 */
	public function update($data=null)
	{
		$pk=$this->model->getPk();//获得这个模块的主键，一定要有主键才可以使用
		$id=$_REQUEST[$pk];  //存放要删除的ID，可以多个
		if(isset($id)){
			/*修改并删除以前的图片开始*/
			$result = $this->get_fields_model()->where(array($pk=>$id))->find();
			if($result !== false || $result  != null){
				if($this->config['img_fields']){
					$img_fields = explode(',', $this->config['img_fields']);
					foreach ($img_fields as $value){
						if(in_array($value, $this->fields)){
							if($_FILES[$value]['name']== ''){
								unset($_POST[$value]);
							}else{
								$this->delfile($result[$value]);
								$this->fileUpload($value);//保存当前图片
							}
						}
					}
				}
			}else{
				util_404();
			}
				
			if($data === null){
				if($this->model->create() && $this->model->save() !== false){
					return  $this->config['show']== false ? 1 : $this->show_redirect();
				}else{
					return  $this->config['show'] == false ? 0 : $this->show_redirect();
				}
			}else{
				$map['id'] = $data[$pk];
				unset($data[$pk]);
				if($this->model->where($map)->save($data) !== false){
					return  $this->config['show']== false ? 1 : $this->show_redirect();
				}else{
					return  $this->config['show'] == false ? 0 : $this->show_redirect();
				}
			}
		}else{
			util_404();
		}
	}
	
	/**
	* 批量修改（注：目前没有做批量修改中对原始图片的删除）
	*@param
	*@author  Eayon
	*@since 1.0
	*@return 
	*/
	public function updateAll($data){
		$pk=$this->model->getPk();//获得这个模块的主键，一定要有主键才可以使用
		$id=$_REQUEST[$pk];  //存放要删除的ID，可以多个
		if(isset($id)){
			$condition = array($pk=>array('in',explode(',',$id))); //删除条件，形如 id in 1,2,5,6....
			$map[$pk] = array('in',$condition);
			if($this->model->where($condition)->save($condition) !== false){
				return  $this->config['show']== false ? 1 : $this->show_redirect();
			}else{
				return  $this->config['show'] == false ? 0 : $this->show_redirect();
			}
		}else{
			util_404();
		}
	}
	
	/**
	 *添加一个记录的时候判断是不是需要排序如果要，那么就要先计算排序的字段值
	 *@param
	 *@author  Eayon
	 *@since 1.0
	 *@return
	 */
	public function _before_update(){
		$updateTime = 'updateTime';
		
		/*如果没有排序字段就用做任何处理*/
		if(!in_array($updateTime, $this->fields)){
			return ;
		}
		
		$time = date('y-m-d h:i:s',time());
		
		//给排序值赋值
		if (! empty ( $_POST )){
			$_POST[$updateTime] = $time;
		}else{
			$_GET[$updateTime] =$time;
		}
	}
	
	/**
	* 通过主键获取某个记录的内容
	*@param
	*@author  Eayon
	*@since 1.0
	*@return 
	*/
	public function bean(){
		$id = I('id');
		$this->map = $this->_search (); // 生成查询对象
		$this->map['id'] = $id;//添加id条件
			
		$list = $this->model// 进行分页数据查询
		->where ($this->map);
		
		if($this->config['relation']){//是否需要使用关联模型
			$list = $list->relation($this->config['relation']);
		}
			
		if($this->config['res_fields']){
			$list = $list->field($this->config['res_fields']);
		}else if($this->config['res_not_fields']){
			$list = $list->field($this->config['res_not_fields'],true);
		}
		
		$bean = $list ->find();
		$this->vo = $bean;
		$this->assign ( 'vo', $bean );
		$this->rand = util_rand_number();
		$this->show_dispaly();
	}
	
	/**
	* 获取到数据列表 ，需要先调用index方法才可以
	*@param
	*@author  Eayon
	*@since 1.0
	*@return 
	*/
	protected  function getList(){
		return $this->list;
	}
	
	
    /**
    * 每个模块的入口，也是默认查询的如果
    *@author  Eayon
    *@since 1.0
    */
	public function index() {
		if (! $this->notModule) {//如果需要就进行数据返回，否则直接输出
			if($this->config['search']){
				 $this->map = $this->_search (); // 生成查询对象
			}
// 			dump($this->map);
// 			die();
			$this->_list (); // 获得数据列表
		}
	    $this->show_dispaly();
	}
	
	/**
	*  说明：对记录做排序
	参数：
	$id:当前记录的id
	$sort_type [String] desc(降序)  asc(升序)
	$tag [Int] 上移还是下移， 0(下移) 1(上移) 2(置顶)
	$sort[Int] 当前记录排序的值
	$id[Int] 当前记录的id
	*@param
	*@author  Eayon
	*@since 1.0
	*@return 
	*/
	public function sort($id,$sort,$tag,$sort_type = 'desc'){
		 
		if($this->display_name == ''){//排序页面默认跳转
			$this->display_name = 'index';
		}
		 
		$map = $this->_search();//获得查询字段
		 
		if(($sort_type == 'desc' && ($tag==1 ||$tag==2) ) || ($sort_type == 'asc' && $tag==0) ){//确定需要调换的记录
			$map[$this->config['sort']] = array('GT',$sort);
		}else {
			$map[$this->config['sort']] = array('LT',$sort);
		}
	
		if( $tag==1){//如果是上移，改变排序方案获取值
			$sort_type == 'desc'?$sort_type='asc':$sort_type='desc';
		}
	
		unset($map['id']);
		if($tag == 2){
			$info = $this->model->limit(1)->order($this->config['sort'].' '.$sort_type)->find();
		}else{
			$info = $this->model->where($map)->limit(1)->order($this->config['sort'].' '.$sort_type)->find();
		}
		 
		if($info == '' || $info == null){//如果没有纪录的内容了，就不用排序了
			//将条件值设置为空，不产生条件查询
			$_GET['id'] = '';
			$_GET[$this->config['sort']] = '';
			$_GET['tag'] = '';
			$this->index();
			return ;
		}
		 
		$map_now[$this->config['sort']] = $sort;
		$map_now['id'] = $id;
		$map_update[$this->config['sort']] = $info['sort'];
		$map_update['id'] = $info['id'];
		 
		if($tag == 2){//置顶操作
			if($sort_type == 'desc'){
				$this->model ->where($map_now)->setField($this->config['sort'],$info['sort']+1);
			}else{
				$this->model ->where($map_now)->setField($this->config['sort'],$info['sort']-1);
			}
		}else{//上下移动操作
			$this->model->startTrans();
			$result1 = $this->model ->where($map_now)->setField($this->config['sort'],0);
			$result2  = $this->model ->where($map_update)->setField($this->config['sort'],$map_now['sort']);
			unset($map_now[$this->config['sort']]);//条件改变了，变成0，不需要了
			$result3 = $this->model ->where($map_now)->setField($this->config['sort'],$map_update['sort']);
			if( $result1 && $result2 && $result3){
				$this->model->commit();
			}else{
				$this->model->rollback();
			}
		}
		 
		$_GET['id'] = '';
		$_GET[$this->config['sort']] = '';
		$_GET['tag'] = '';
	
		$this->index();
	}
	

	
	/**
	* 页面显示返回
	*@param
	*@author  Eayon
	*@since 1.0
	*@return 
	*/
	public  function show_dispaly(){
		if($this->config['show']){//判断是否需要显示
				$this->display ($this->config['display']);
		}
	}
	
	/*-----------------------------------------------/
	 说明：跳转页面
	/-------------------------------------------------*/
	private function show_redirect(){
	if($this->config['show']){//判断是否需要显示
				$this->redirect ($this->config['display'],$this->config['display_parms']);
		}
	}
	
	
	/**
	* 初始化数据主要是  notModule，model，fields属性
	*@param
	*@author  Eayon
	*@since 1.0
	*@return 
	*/
	private function init(){
		$this->config = array(
				'show'=>true,//是否需要显示页面，默认直接显示
				'relation'=>false,//是否需要使用关联查询，如果需要传入的字段格式如下'UserModel,ActivityModel'
				'page'=>true,//是否需要分页查询
				'fuzzy'=>false,//模糊查询字段条件的格式'name,username,...'
				'display'=>'',//当前返回的视图，如果没有设置，默认系统字段获取当前视图
				'search'=>true,//是否取用条件查询，启用之后会自动获取前台转入的字段
				'neglect_fields '=>false,//操作需要忽略的字段，比如做查询条件的时候不能前台传name字段进来，则设置'name',或者添加内容的时候不能添加的字段
				'res_fields'=>false,//设置数组一级目录可以返回的字段的名字，如果没有设置就会把所有的字段返回回来
				'res_not_fields'=>false,//设置不能返回到前台的字段，如果有设置'res_fields',则字段忽略'res_not_fields'
				'M_D'=>'D',//使用什么方法实例化，默认是D方法
				'sort'=>'sort',//排序字段默认使用sort
				'img_fields'=>false,//数据库表中的图片字段默认情况就这两个，做删除操作的时候用的上false表示没有图片需要删除
				'del_field'=>'is_del',//删除字段，如果表里面有这个字段默认有软删除操作，否则字节删除
				'page_listrows'=>13,//分页每页需要多少数据
				'var_page'=>'page',//页码标识符，一般不需要修改
				'display_parms'=>array(),//当显示为redirect从定向时有效
				'between_time'=>'createTime',
				'model_name'=>CONTROLLER_NAME,
				'insert_time'=>'createTime,updateTime',
				'excel'=>false,//导入配置:'excel'=>array('import'=>array('A'=>'password','B'=>'name','C'=>'grade')),A,B,C表示第一,二,三列
				//导出:'excel'=>array('headArr'=>array('序号'=>'id','姓名'=>'name','年龄'=>'grade'),'output'=>array('A'=>'id','B'=>'name','C'=>'grade')),headArr表头
		);
		       $this->setModel();
       }
       
       /**
       * 设置model
       *@param
       *@author  Eayon
       *@since 1.0
       *@return 
       */
       private function setModel(){
	       	$name = $this->config['model_name']; // 获取模块的名字
	       	if ($this->config['M_D'] == 'M') {//如果需要就进行数据返回，否则直接输出
	       		$this->model =M( $name) ;// 获得模型对象
	       	}else{
	       		$this->model =D( $name) ;// 获得模型对象
	       	}
	       	$this->fields = $this->model->getDbFields(); // 获得模型下面的所有的字段
       }
       


	
	
	/*说明：生成查询对象  */ 
	private  function _search() {
		$now_fields = $this->fields;
		if($this->config['neglect_fields']){
			$arr = explode(',' , $this->config['neglect_fields']);
			$now_fields = [];
			foreach ($this->fields as $key => $value) {
				if(!in_array($value, $arr)){
					array_push($now_fields,$value);
				};
			}
		}
		
		//处理时间查询区间
		$between_time_start = I ( 'between_time_start');
		$between_time_end =  I ('between_time_end') ;
		 if((($between_time_start  !='' && $between_time_start  !=null)  || ($between_time_end  !='' && $between_time_end  !=null) ) &&  in_array($this->config['between_time'], $now_fields) ){
			$start = 	$between_time_start != ''? $between_time_start:'2000-10-10';
			$end =    $between_time_end != ''? $between_time_end:'3000-10-10';
			$start = strtotime($start);
			$end = strtotime($end);
		 	$map[$this->config['between_time']] = array('between',"$start,$end");
		} 
		
		if($this->config['between_time_int']){
			$start =$this->config['start_1'];
			$end = $this->config['end_1'];
			$map[$this->config['between_time_int']] = array('between',"$start,$end");
		}
		foreach ( $now_fields as $key => $val ) {		// 获得和数据库一样的字段
			if($val == $this->config['sort']){//判断是否有排序字段
				$this->order = $this->config['sort'];//保存排序字段排序用
			}
			
			$from_val = I ( $val );
			if ($from_val != '') {//数据库有这个字段
				if($this->config['fuzzy'] != false){
					$i = 0; 
					$arr = explode(',', $this->config['fuzzy']);
					foreach ($arr as $key=>$value){
						if($value == $val ){//判断是否有模糊查询的字段
							$map [$val] = array('like','%'.urldecode($from_val).'%');
							$i = 1; 
							break;
						}
					}
					//如果不存在这个模糊查询字段，直接加入查询
					if($i == 0){
						$map [$val] =urldecode($from_val);
					}
				}else{
					$map [$val] = urldecode($from_val);
				}
			}
		}
		
		if($this->config['del_field'] &&  in_array($this->config['del_field'], $this->fields)){//判断是否需要把删除的内容显示出来
			$map[$this->config['del_field']] = 0;
		}
		//条件查旬
		if($this->config['where_in']){
			$map[$this->config['where_in']]= $this->config['where_in_value'];
		}
		//条件查旬
		if($this->config['ids_in']){
			$map[$this->config['ids_in']]= array('in',$this->config['ids_in_str']);
		}
		
		if($this->config['where_string']){
			$map[$this->config['where_string']]= $this->config['where_string_value'];
		}
		
		return $map;
	}
	
	
	/*
	 * 说明：数据显示及分页等数据处理，并返回前台
	 */
	public function _list() {
		// 排序字段，默认为主键名
		//外键的优先级（用户自定义-》系统默认-》主键名）
		$order = I ( '_order' ) != '' ? I ( '_order' ) : ($this->order !=''?$this->order : $this->model->getPk ());
		$sort = I ( '_sort' ) == 'asc' ? 'asc' : 'desc';	// 默认倒序
		/*对分页进行处理*/
		$count = $this->model->where ( $this->map )->count ();	// 取得记录的数量
// 		dump($count);
// 		die();
	//对数据统计
		if($this->config['statistics']){
			if(is_array($this->config['statistics'])){
				foreach ($this->config['statistics'] as $key_s => $value_s) {
					$this->$value_s=$this->model->where ( $this->map )->sum($value_s);//对该字段求和
				}
			}else{
				$this->statistics=$this->model->where ( $this->map )->sum($this->config['statistics']);//对该字段求和
			}
		}
// 		dump($this->statistics);
// 		die();
		if ($count > 0) {	// 有数据才去查
			$listRows = I ( 'numPerPage' ) != '' ? I ( 'numPerPage' ) : $this->config['page_listrows'];// 获得每页的行数
			
			$page = new  \Org\Util\PageForIndex ($listRows,'table=1');
			$page->init($count);
		/* 	$page->setHtml(array(
					4=>'<a href="%uri&page=%page" class="btn x-large ui-state-default"><i class="glyph-icon icon-chevron-left"></i></a>', //上一页按钮
					5=>'<a href="%uri&page=%page" class="btn x-large ui-state-default">%page</a>',//当前的页码列表
					6=>'<a href="%uri&page=%page" class="btn x-large ui-state-default"><i class="glyph-icon icon-chevron-right"></i></a>',//下一页按钮
					9=>'<a href="%uri&page=%page" class="btn x-large disabled ui-state-default">%page</a>',//当前的页面（在页码列表里面的状态）
			)); */
			
// 			$page->setHtml(array(
// 					3=>'<a tabindex="0"  form-type="table"  form-method = "get"  href = "%uri&page=1&table=table" class="first ui-corner-tl ui-corner-bl fg-button ui-button ui-state-default " id="DataTables_Table_0_first">首页</a>',
// 					4=>'<a tabindex="0" form-type="table"  form-method = "get"   href = "%uri&page=%page&table=table" class="previous fg-button ui-button ui-state-default ui-state-disabled" id="DataTables_Table_0_previous">上一页</a>', //上一页按钮
// 					5=>'<a tabindex="0" form-type="table"  form-method = "get"   href = "%uri&page=%page&table=table" class="fg-button ui-button ui-state-default ">%page</a>',//当前的页码列表
// 					6=>'<a tabindex="0"  form-type="table"  form-method = "get"  href = "%uri&page=%page&table=table" class="next fg-button ui-button ui-state-default" id="DataTables_Table_0_next">下一页</a>',//下一页按钮
// 					7=>'<a tabindex="0"  form-type="table"  form-method = "get"   href = "%uri&page=%page&table=table" class="last ui-corner-tr ui-corner-br fg-button ui-button ui-state-default" id="DataTables_Table_0_last">尾页</a>',
// 					9=>'<a tabindex="0"  form-type="table"  form-method = "get"  href = "%uri&page=%page&table=table" class="fg-button ui-button ui-state-default ui-state-disabled">%page</a>',//当前的页面（在页码列表里面的状态）
// 			));
			$page->setHtml(array(
					3=>"<a tabindex='0'  form-type='table'  form-method = 'get'  href = '%uri&page=1&table=table&between_time_start=".$this->between_time_start."&between_time_end=".$this->between_time_end."' class='first ui-corner-tl ui-corner-bl fg-button ui-button ui-state-default' id='DataTables_Table_0_first'>首页</a>",
					4=>"<a tabindex='0' form-type='table'  form-method = 'get'   href = '%uri&page=%page&table&between_time_start=".$this->between_time_start."&between_time_end=".$this->between_time_end."' class='previous fg-button ui-button ui-state-default ui-state-disabled' id='DataTables_Table_0_previous'>上一页</a>", //上一页按钮
					5=>"<a tabindex='0' form-type='table'  form-method = 'get'   href = '%uri&page=%page&table=table&between_time_start=".$this->between_time_start."&between_time_end=".$this->between_time_end."' class='fg-button ui-button ui-state-default '>%page</a>",//当前的页码列表
					6=>"<a tabindex='0'  form-type='table'  form-method = 'get'  href = '%uri&page=%page&table=table&between_time_start=".$this->between_time_start."&between_time_end=".$this->between_time_end."' class='next fg-button ui-button ui-state-default' id='DataTables_Table_0_next'>下一页</a>",//下一页按钮
					7=>"<a tabindex='0'  form-type='table'  form-method = 'get'   href = '%uri&page=%page&table=table&between_time_start=".$this->between_time_start."&between_time_end=".$this->between_time_end."' class='last ui-corner-tr ui-corner-br fg-button ui-button ui-state-default' id='DataTables_Table_0_last'>尾页</a>",
					9=>"<a tabindex='0'  form-type='table'  form-method = 'get'  href = '%uri&page=%page&table=table&between_time_start=".$this->between_time_start."&between_time_end=".$this->between_time_end."' class='fg-button ui-button ui-state-default ui-state-disabled'>%page</a>",//当前的页面（在页码列表里面的状态）
			));
			
			$show = $page->fpage(array(3,4,5,6,7));
			$currentPage = I ( $this->config['var_page'] ) != ''  ?  I ( $this->config['var_page'] ) : 1;	// 当期的页码
			
			/*获得数据列表*/
			$list = $this->model
			->where ( $this->map )
			->order ( $order . ' ' . $sort );
		
			
// 			dump($this->model->_sql());
			if($this->config['page']){//判断是否需要分页显示
				 $list = $list->page ( $currentPage . ',' . $listRows );
			}
			
			if($this->config['relation']){//是否需要使用关联模型
				$list = $list->relation($this->config['relation']);
			}
			
		 	if($this->config['res_fields']){
				$list = $list->field($this->config['res_fields']);
			}else if($this->config['res_not_fields']){
				$list = $list->field($this->config['res_not_fields'],true);
			} 
			$list = $list->select();
			$this->list = $list;
			
             /*页面显示部分*/
			$sortImg = $sort; // 排序标记
			$sortAlt = $sort == 'desc' ? '升序排列' : '倒序排列'; // 排序提示
			$sort = $sort == 'desc' ? 1 : 0; // 排序方式
			/* dump($this->list); */
			
			 /*输出*/        
			$this->assign ( 'list', $list );
			$this->assign ( 'sort', $sort );
			$this->assign ( 'order', $order );
			$this->assign ( 'sortImg', $sortImg );
			$this->assign ( 'sortType', $sortAlt );
			$this->assign ( 'page', $show ); // 分页输出
			$this->assign ( 'goPage', $page->get_go_page() ); // 分页输出
			$this->assign ( 'totalCount', $count );
			$this->assign ( 'totalPage', ceil($count/$listRows));
			$this->assign ( 'numPerPage',$listRows );//每页显示的数量
			$this->assign ( 'currentPage', $currentPage );//当前页码
			
			
		}
	}
	
   /*-----------------------------------------------/
	说明：处理上传的图片
	 参数：
	 $imgUrl:表单的图片参数
	/-------------------------------------------------*/
	function fileUpload($imgUrl = "imgUrl",$path=null){
		//判断附件是否有上传
		//如果有则实例化Upload，把附件上传到服务器指定位置
		//然后把附件的路径名获得到，存入$_POST
		if(!empty($_FILES)){
			if($path==null){
				$config = array(
						'rootPath'      =>     './Public/',  //根目录
						'savePath'      =>     '/matrix/upload/', //保存路径
				);
			}else{
				$config = array(
						'rootPath'      =>     './Public/',  //根目录
						'savePath'      =>     '/matrix/upload/'.$path.'/', //保存路径
				);
			}
			
			//附件被上传到路径：根目录/保存目录路径/创建日期目录
			$upload = new \Think\Upload($config);
			//uploadOne会返回已经上传的附件信息
			$z = $upload -> uploadOne($_FILES[$imgUrl]);
			if(!$z){
				$upload->getError(); //获得上传附件产生的错误信息
				return false;
			}else {
				//拼装图片的路径名
				$bigimg = $z['savepath'].$z['savename'];
				$srcimg = $upload->rootPath.$bigimg;
				IS_POST?$_POST[$imgUrl] = $bigimg:$_GET[$imgUrl] = $bigimg;
				
				return array(
					'absolute_'.$imgUrl => $srcimg,//全路劲
					'savepath'=>$z['savepath'],//保存的路劲
					'savename'=>$z['savename'],//保存图片的名字
					'rootPath'=>$upload->rootPath,//根目录
				);
				
				/* if($is_small){
		 				//把已经上传好的图片制作缩略图Image.class.php
		 				$image = new \Think\Image();
		 				//open();打开图像资源，通过路径名找到图像
		 				$srcimg = $upload->rootPath.$bigimg;
		 				$image -> open($srcimg);
		 				$image -> thumb(150,150);  //按照比例缩小
		 				$smallimg = $z['savepath']."small_".$z['savename'];
		 				$image -> save($upload->rootPath.$smallimg);
		 				$_POST[$imgUrl."_small"] = $smallimg;
				} */
			}
		}
	}
	
	
	/*-----------------------------------------------/
	 说明：删除数据库的图片
	参数：
	$imgUrl:表单的图片参数
	/-------------------------------------------------*/
	protected  function delfile($imgUrl = ""){
		if($imgUrl){//检查图片文件是否存在
			$filename = "./Public".$imgUrl;  //给图片地址拼接成完整路径
			$img_suffix = strrchr($imgUrl,'.');//获取图片后缀
			$img_suffix_name = array('.jpg','.JPG','.jpeg','.JPEG','.gif','.GIF','.png','.PNG','.mp3');
			if(!in_array($img_suffix,$img_suffix_name)){//判断是不是图片资源
				return false;
			}
			if(file_exists($filename))//判断路径是不是存在,不存在也返回true无需删除
			{
				if(!unlink($filename)){//删除图片
					return false;	//删除失败!
				}
			}
		}
		return true;
	}
	
	
	/*-----------------------------------------------/
	 说明：删除编辑框的图片
	参数：
	$imgUrl:表单的编辑框参数
	/-------------------------------------------------*/
	//删除编辑框里面的图片
	function delUeditorImg($content = "content"){
		$str = html_entity_decode($content);
		$html = str_get_html($str);
		foreach($html->find('img') as $element)
		{
			$res1 = $element->src;
			$res2 = substr_replace(__APP__,'',-9);
			$res3 = substr_replace($res1,'./',0,strlen($res2));
			$res = unlink($res3);
		}
	}
	/*-----------------------------------------------/
	 说明：删除编辑框的附件
	参数：
	$imgUrl:表单的编辑框参数
	/-------------------------------------------------*/
	//删除编辑框里面的图片
	function delUeditorFile($content = "content"){
		$str = html_entity_decode($content);
		$html = str_get_html($str);
		foreach($html->find('a') as $element)
		{
			$res1 = $element->href;
			$res2 = substr_replace(__APP__,'',-9);
			$res3 = substr_replace($res1,'./',0,strlen($res2));
			$res = unlink($res3);
		}
	}
    
    
    
    
    /**
    * 对model进行处理，给model添加查询时候的字段
    *@param
    *@author  Eayon
    *@since 1.0
    *@return 
    */
    private function get_fields_model(){
    	if($this->config['res_fields']){
    		return $this->model->field($this->config['res_fields']);
    	}else if($this->config['res_not_fields']){
    	   return $this->model->field($this->config['res_fields'],true);
    	}else{
    		return $this->model;
    	}
    }

    
	/* (non-PHPdoc)
	 * @see \Org\Recour\RecourController::no_login()
	 */
	protected function no_login() {
		if(IS_AJAX){
			$data['login_url'] = "__APP__/Admin/User/login";
			$map['error'] = 	$data['login_url'];
			echo json_encode($map);
			die();
		}else{
			$this->redirect('User/login');
		}
	}

	/* (non-PHPdoc)
	 * @see \Org\Recour\RecourController::no_auth()
	 */
	protected function no_auth() {
		if(IS_AJAX){
			$data['login_url'] = "__APP__/Admin/User/login";
			$map['error'] = 	$data['login_url'];
			echo json_encode($map);
			die();
		}else{
				$this->redirect('User/login');
		}
	}
	
	protected  function system_hint($content,$code,$exit=1){
		  $map['yunshao_system_hint_20151109'] = array(
		  	   'content'=>$content,
		  		'code'=>$code,
		  		'exit'=>$exit,
		  );
		  die(json_encode($map));
	}
	
	protected function error(){
		$this->redirect('Index/error');
	}
	
	/**
	 * 函数用途描述:excel导入读取数据并返回数组
	 * @date: 2015-10-29
	 * @author:RongShu
	 * @param:
	 * @return:插入的s首条数据id
	 */
	public function excelImport(){
// 		if(!$this->config['excel'] || !isset($this->config['excel']['import'])){
// 			return false ;
// 		}
// 		$arr = $this->config['excel']['import'];
		$upload = new \Think\Upload();// 实例化上传类
		$upload->maxSize   =     3145728 ;// 设置附件上传大小
		$upload->exts      =     array('xls', 'xlsx');// 设置附件上传类
		$upload->savePath  =      '/'; // 设置附件上传目录
		// 上传文件
		$info   =   $upload->uploadOne($_FILES['excelData']);
		if(empty($_FILES['excelData'])){
			$this->system_hint("导入文件不能为空！", 101);
			return ;
		}
		$filename = './Uploads'.$info['savepath'].$info['savename'];
		$exts = $info['ext'];//获取文件后缀名
		//导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
		import("Org.Util.PHPExcel");
		//创建PHPExcel对象，注意，不能少了\
		$PHPExcel=new \PHPExcel();
		//如果excel文件后缀名为.xls，导入这个类
		if($exts == 'xls'){
			import("Org.Util.PHPExcel.Reader.Excel5");
			$PHPReader=new \PHPExcel_Reader_Excel5();
		}else if($exts == 'xlsx'){
			import("Org.Util.PHPExcel.Reader.Excel2007");
			$PHPReader=new \PHPExcel_Reader_Excel2007();
		}
		
		//载入文件
		$PHPExcel=$PHPReader->load($filename);
		//获取表中的第一个工作表，如果要获取第二个，把0改为1，依次类推
		$currentSheet=$PHPExcel->getSheet(0);
		//获取总列数
		$allColumn=$currentSheet->getHighestColumn();
		//获取总行数
		$allRow=$currentSheet->getHighestRow();
		//循环获取表中的数据，$currentRow表示当前行，从哪行开始读取数据，索引值从0开始
		for($currentRow=2;$currentRow<=$allRow;$currentRow++){
			//从哪列开始，A表示第一列
			$is_cell_empty=false;
			for($currentColumn='A';$currentColumn<=$allColumn;$currentColumn++){
				//数据坐标
				$address=$currentColumn.$currentRow;
				//读取到的数据，保存到数组$arr中
				$data_e[$currentRow][$currentColumn]=(string)$currentSheet->getCell($address)->getValue();
				if($data_e[$currentRow][$currentColumn]!=''){
					$is_cell_empty=true;
				}
			}
			if(!$is_cell_empty){
				unset($data_e[$currentRow]);//如果是空行，则删除
			}
		}
		unlink($filename);//获取数据后删除上传文件
		//查数据库去重复的
		foreach ($data_e as $key => $value) {
			$codeModel = D("Code");
			$where_code['date']=$value['A'];
			$where_code['date_num']=$value['B'];
			$code_r_f = $codeModel->where($where_code)->find();
			if($code_r_f){
				unset($data_e[$key]);
			}
		}
		//将导入数据完善成全部数据
		$data_all=array();//补全后的数据
			foreach ($data_e as $key_e => $value_e) {
				$p1 = getNumberAll($value_e['C'],false,$value_e['A'])[0];
				$p2 = getNumberAll($value_e['D'],false,$value_e['A'])[0];
				$p3 = getNumberAll($value_e['E'],false,$value_e['A'])[0];
				$p4 = getNumberAll($value_e['F'],false,$value_e['A'])[0];
				$p5 = getNumberAll($value_e['G'],false,$value_e['A'])[0];
				$p6 = getNumberAll($value_e['H'],false,$value_e['A'])[0];
				$tm = getNumberAll($value_e['I'],true,$value_e['A'])[0];
				$data['date']=$value_e['A'];
				$temp_y = substr($value_e['A'],0,4);
				$temp_m = substr($value_e['A'],5,2);
				$temp_r = substr($value_e['A'],8,2);
				$data['new_date']=$temp_y.'年'.$temp_m.'月'.$temp_r.'日';
				$data['old_date']= $tm['old_time'][4].'月'.$tm['old_time'][5].'日';
				$data['date_num']=$value_e['B'];
				//星期
				$rows=array("星期日","星期一","星期二","星期三","星期四","星期五","星期六");
				$week_num = date("w",strtotime($value_e['A']));//星期
				$data['week']=$rows[$week_num];
				$data['p_1']=$p1['number'];
				$data['x_1']=$p1['sx'];
				$data['b_1']=$p1['bs'];
				$data['p_2']=$p2['number'];
				$data['x_2']=$p2['sx'];
				$data['b_2']=$p2['bs'];
				$data['p_3']=$p3['number'];
				$data['x_3']=$p3['sx'];
				$data['b_3']=$p3['bs'];
				$data['p_4']=$p4['number'];
				$data['x_4']=$p4['sx'];
				$data['b_4']=$p4['bs'];
				$data['p_5']=$p5['number'];
				$data['x_5']=$p5['sx'];
				$data['b_5']=$p5['bs'];
				$data['p_6']=$p6['number'];
				$data['x_6']=$p6['sx'];
				$data['b_6']=$p6['bs'];
				$data['tm']=$tm['number'];
				$data['sx']=$tm['sx'];
				$data['ds']=$tm['ds'];
				$data['bs']=$tm['bs'];
				$data['dx']=$tm['dx'];
				$data['wx']=$tm['wx'];
				$data['tt']=$tm['tt'];
				$data['ws']=$tm['ws'];
				$data['hds']=$tm['hds'];
				$data['jy']=$tm['jy'];
				$data['ms']=$tm['ms'];
				$data['dw']=$tm['dw'];
				$data['yy']=$tm['yy'];
				$data['td']=$tm['td'];
				$data['jx']=$tm['jx'];
				$data['hb']=$tm['hb'];
				$data['sex']=$tm['sex'];
				$data['bh']=$tm['bh'];
				$data['nv']=$tm['nv'];
				$zh = $value_e['C']+$value_e['D']+$value_e['E']+$value_e['F']+$value_e['G']+$value_e['H']+$value_e['I'];
				if($zh<=175){
					$data['zh']='('.$zh.')≤176';
				}else {
					$data['zh']='('.$zh.')≥175';
				}
				$zh_gw = substr($zh,-1);//总和个位
				if(($zh_gw%2)==0){
					$data['zhds']='双';
				}else{
					$data['zhds']='单';
				}
				array_push($data_all, $data);
			}
		$res = $this->model->addAll($data_all);
		return  $this->config['show']?$this->show_redirect() : $res;
	}
	
	function excelImportCheck($phone,$db_fieldname){
		return false;
	}
	/**
	 * 函数用途描述:excel导出
	 * @date: 2015-10-29
	 * @author:RongShu
	 * @param:
	 * @return:
	 */
	public function excelOutput(){
		if(!$this->config['excel'] || !isset($this->config['excel']['output'])){
			return false ;
		}
		$arr = $this->config['excel']['output'];//数据对应关系
		$headArr = $this->config['excel']['headArr'];//头部需要放数据
		$where = $this->config['excel']['select'];//导出数据条件
		$relation = $this->config['excel']['relation'];//导出数据条件
		if($relation){
			$list = $this->model->where($where)->relation(true)->select();
		}else {
			$list = $this->model->where($where)->select();
		}
		//准备内容数据
		$data = array();
		foreach ($list as $key=>$value){
			foreach ($arr as $key_model => $value_model){
				$data[$key][$value_model] = $value[$value_model];
			}
		}
		//准备头部数据
		foreach ($data as $key1=>$value1){
			foreach ($headArr as $key_head =>$value_head){
				if($key1 ==$value_head){
					$head[]=$key_head;
				}
			}
		}
		//导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
		import("Org.Util.PHPExcel");
		import("Org.Util.PHPExcel.Writer.Excel5");
		import("Org.Util.PHPExcel.IOFactory.php");
		$date = date("Y_m_d",time());
		$fileName .= "{$date}.xls";
		//创建PHPExcel对象，注意，不能少了\
		$objPHPExcel = new \PHPExcel();
		$objProps = $objPHPExcel->getProperties();
		//设置表头
		$key = ord("A");
		foreach($head as $v){
			$colum = chr($key);
			$objPHPExcel->setActiveSheetIndex(0) ->setCellValue($colum.'1', $v);
			$objPHPExcel->setActiveSheetIndex(0) ->setCellValue($colum.'1', $v);
			$key += 1;
		}
		//写入内容
		$column = 2;
		$objActSheet = $objPHPExcel->getActiveSheet();
		foreach($data as $key => $rows){ //行写入
			$span = ord("A");
			foreach($rows as $keyName=>$value){// 列写入
				$j = chr($span);//从A2,B2...
				$objActSheet->setCellValue($j.$column, $value);
				$span++;
			}
			$column++;
		}
		//重命名表
		$fileName = iconv("utf-8", "gb2312", $fileName);
		//设置活动单指数到第一个表,所以Excel打开这是第一个表
		$objPHPExcel->setActiveSheetIndex(0);
		ob_end_clean();//清除缓冲区,避免乱码
		header('Content-Type: application/vnd.ms-excel');
		header("Content-Disposition: attachment;filename=\"$fileName\"");
		header('Cache-Control: max-age=0');
		
		$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
		$objWriter->save('php://output'); //文件通过浏览器下载                                                                             
		exit;
	}
	//进入系统前的过滤
	abstract protected function init_show();
}